import os
from ftplib import FTP, error_perm

ANONYMOUS = "anonymous"

class FtpSender(object):
	def __init__(self, host = None, user = None, passwd = None):
		self.__def_att(host, user, passwd)

	def __def_att(self, host, user, passwd):
	
		self.__ftphdler = None

		if host == None:
			return None		

		self.__host = host
		self.__port = 21

		if user == None:
			self.__user = ANONYMOUS
			self.__passwd = ANONYMOUS
		else:
			self.__user = user
			self.__passwd = passwd


	def ConnectOnPort(self, host = None, user = None, passwd = None, port = None):
		if port != None:
			self.__port = port
		return self.__Connect(host, user, passwd)
		

	def Connect(self, host = None, user = None, passwd = None):
		if self.__ftphdler != None:
			self.__Disconnect()

		self.__def_att(host, user, passwd)
			
		try:
			self.__ftphdler = FTP()
			self.__ftphdler.connect(self.__host, self.__port)	
			self.__ftphdler.login(self.__user, self.__passwd)
			return (True, '')
		except error_perm, e:
			# Control de Error
			return (False, e)						


	def Cwd(self, path):
		if self.__ftphdler != None:
			try:
				self.__ftphdler.cwd(path)
				return (True, '')
			except error_perm, e:
				# Agregar control de errores
				return (False, e)


	def Disconnect(self):
		if self.__ftphdler != None:
			self.__ftphdler.close()
			self.__ftphdler = None


	def Send(self, srcfile = None, dstfile = None, pasv = True):
		
		if self.__ftphdler == None:
			# Informar algun error
			return (0, '')
			
		if os.path.isfile(srcfile) and dstfile != None:
			try: 
				fhdler = open(srcfile, "rb")
				self.__ftphdler.set_pasv(pasv)
				self.__ftphdler.storbinary('STOR' + ' ' + dstfile, fhdler)
				size = self.__ftphdler.size(dstfile)
				fhdler.close()
				return (size, '')

			except error_perm, e:
				# Control de errores
				return -1, e			

